import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
from datetime import datetime, timedelta
from utils.time_utils import calculate_reminder_time, format_time
from utils.config import CATEGORIES

class EventDialog:
    def __init__(self, parent, event_id=None):
        self.result = None
        self.top = tk.Toplevel(parent)
        self.top.title("Add Event" if event_id is None else "Edit Event")
        self.top.geometry("500x500")
        self.top.transient(parent)
        self.top.grab_set()
        
        # 创建表单
        self.create_form(event_id)
        
        # 保存按钮
        btn_frame = ttk.Frame(self.top)
        btn_frame.pack(pady=10)
        ttk.Button(btn_frame, text="Save", command=self.save).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="Cancel", command=self.top.destroy).pack(side=tk.LEFT, padx=5)
    
    def create_form(self, event_id):
        # 标题
        ttk.Label(self.top, text="Title:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
        self.title_entry = ttk.Entry(self.top, width=40)
        self.title_entry.grid(row=0, column=1, padx=5, pady=5)
        
        # 描述
        ttk.Label(self.top, text="Description:").grid(row=1, column=0, sticky="nw", padx=5, pady=5)
        self.desc_text = scrolledtext.ScrolledText(self.top, width=40, height=4)
        self.desc_text.grid(row=1, column=1, padx=5, pady=5)
        
        # 事件时间
        ttk.Label(self.top, text="Event Time:").grid(row=2, column=0, sticky="w", padx=5, pady=5)
        self.event_time_entry = ttk.Entry(self.top, width=20)
        self.event_time_entry.grid(row=2, column=1, padx=5, pady=5)
        self.event_time_entry.insert(0, datetime.now().strftime("%Y-%m-%d %H:%M"))
        
        # 提醒时间
        ttk.Label(self.top, text="Reminder Time:").grid(row=3, column=0, sticky="w", padx=5, pady=5)
        self.reminder_time_entry = ttk.Entry(self.top, width=20)
        self.reminder_time_entry.grid(row=3, column=1, padx=5, pady=5)
        # 默认提前30分钟
        reminder_time = calculate_reminder_time(self.event_time_entry.get(), 30)
        self.reminder_time_entry.insert(0, reminder_time)
        
        # 分类
        ttk.Label(self.top, text="Category:").grid(row=4, column=0, sticky="w", padx=5, pady=5)
        self.category_var = tk.StringVar()
        self.category_combobox = ttk.Combobox(
            self.top, 
            textvariable=self.category_var, 
            values=list(CATEGORIES.values()),
            state="readonly"
        )
        self.category_combobox.grid(row=4, column=1, padx=5, pady=5)
        self.category_combobox.current(0)  # 默认选中第一个
        
        # 重复类型
        ttk.Label(self.top, text="Recurring:").grid(row=5, column=0, sticky="w", padx=5, pady=5)
        self.recurring_var = tk.StringVar()
        self.recurring_combobox = ttk.Combobox(
            self.top, 
            textvariable=self.recurring_var, 
            values=["None", "daily", "weekly", "monthly"],
            state="readonly"
        )
        self.recurring_combobox.grid(row=5, column=1, padx=5, pady=5)
        self.recurring_combobox.current(0)
        
        # 重复结束日期
        ttk.Label(self.top, text="End Date (for recurring):").grid(row=6, column=0, sticky="w", padx=5, pady=5)
        self.end_date_entry = ttk.Entry(self.top, width=20)
        self.end_date_entry.grid(row=6, column=1, padx=5, pady=5)
        
        # 事件ID（仅编辑时显示）
        if event_id:
            ttk.Label(self.top, text="Event ID:").grid(row=7, column=0, sticky="w", padx=5, pady=5)
            self.event_id_label = ttk.Label(self.top, text=event_id)
            self.event_id_label.grid(row=7, column=1, padx=5, pady=5)
    
    def save(self):
        title = self.title_entry.get().strip()
        desc = self.desc_text.get("1.0", "end-1c").strip()
        event_time = self.event_time_entry.get().strip()
        reminder_time = self.reminder_time_entry.get().strip()
        category = next(k for k, v in CATEGORIES.items() if v == self.category_var.get())
        recurring_type = self.recurring_var.get() if self.recurring_var.get() != "None" else None
        recurring_end_date = self.end_date_entry.get().strip() if self.end_date_entry.get() else None
        
        if not title or not event_time:
            messagebox.showerror("Error", "Title and Event Time are required")
            return
        
        # 验证时间格式
        try:
            datetime.strptime(event_time, "%Y-%m-%d %H:%M")
            datetime.strptime(reminder_time, "%Y-%m-%d %H:%M")
        except ValueError:
            messagebox.showerror("Error", "Invalid date/time format. Use YYYY-MM-DD HH:MM")
            return
        
        self.result = {
            'title': title,
            'description': desc,
            'event_time': event_time,
            'reminder_time': reminder_time,
            'category': category,
            'recurring_type': recurring_type,
            'recurring_end_date': recurring_end_date
        }
        self.top.destroy()